import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { 
  Card, 
  Input, 
  Button, 
  Space, 
  message, 
  Modal, 
  Tabs, 
  Upload,
  Image,
  Tag,
  Divider
} from 'antd';
import { 
  SaveOutlined, 
  EyeOutlined, 
  SendOutlined,
  PictureOutlined,
  FileTextOutlined,
  UploadOutlined
} from '@ant-design/icons';
import RichTextEditor from '../../components/RichTextEditor/RichTextEditor';
import FileUpload from '../../components/FileUpload/FileUpload';
import DocumentManager from '../../components/DocumentManager/DocumentManager';
import { createArticleAPI, updateArticleAPI, getArticleAPI } from '../../apis/article';
import './ArticleEditor.scss';

const { Title } = Input;
const { TabPane } = Tabs;

const ArticleEditor = ({ onSave, onPublish }) => {
  const navigate = useNavigate();
  const { id: articleId } = useParams();
  
  const [article, setArticle] = useState({
    title: '',
    content: { html: '', json: null },
    coverImage: '',
    status: 'draft'
  });
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('editor');
  const [uploadedDocuments, setUploadedDocuments] = useState([]);

  // 加载作品数据
  useEffect(() => {
    if (articleId) {
      loadArticle(articleId);
    }
  }, [articleId]);

  const loadArticle = async (id) => {
    try {
      setLoading(true);
      const response = await getArticleAPI(id);
      if (response.success) {
        const articleData = response.data;
        setArticle({
          title: articleData.title || '',
          content: { 
            html: articleData.content_html || '', 
            json: articleData.content || null 
          },
          coverImage: articleData.cover_image || '',
          status: articleData.status || 'draft'
        });
      } else {
        message.error(response.message || '加载作品失败');
      }
    } catch (error) {
      console.error('加载作品失败:', error);
      message.error('加载作品失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理标题变化
  const handleTitleChange = (e) => {
    setArticle(prev => ({
      ...prev,
      title: e.target.value
    }));
  };

  // 处理内容变化
  const handleContentChange = (content) => {
    setArticle(prev => ({
      ...prev,
      content
    }));
  };

  // 处理封面图片上传
  const handleCoverUpload = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      setArticle(prev => ({
        ...prev,
        coverImage: e.target.result
      }));
      message.success('封面图片上传成功');
    };
    reader.readAsDataURL(file);
    return false;
  };

  // 处理文档上传结果
  const handleFileUploaded = (uploadedFile) => {
    setUploadedDocuments(prev => [...prev, uploadedFile]);
    message.success(`文档 ${uploadedFile.name} 上传完成`);
  };

  // 处理文档删除
  const handleDocumentDelete = (doc) => {
    setUploadedDocuments(prev => prev.filter(item => item.id !== doc.id));
    // 释放文件URL
    if (doc.fileUrl) {
      URL.revokeObjectURL(doc.fileUrl);
    }
    message.success('文档已删除');
  };

  // 插入文档内容到编辑器（仅Word文档）
  const insertDocumentContent = (document) => {
    if (document.type === 'word' && document.html) {
      const currentContent = article.content.html || '';
      const newContent = currentContent + '<br/>' + document.html;
      
      setArticle(prev => ({
        ...prev,
        content: {
          ...prev.content,
          html: newContent
        }
      }));
      
      message.success('Word文档内容已插入到编辑器');
      setActiveTab('editor');
    } else {
      message.info('只有Word文档支持插入到编辑器');
    }
  };

  // 保存草稿
  const handleSave = async () => {
    if (!article.title.trim()) {
      message.error('请输入作品标题');
      return;
    }

    try {
      setLoading(true);
      
      const articleData = {
        title: article.title,
        content: article.content.json,
        content_html: article.content.html,
        cover_image: article.coverImage,
        status: 'draft'
      };

      let response;
      if (articleId) {
        // 更新现有作品
        response = await updateArticleAPI(articleId, articleData);
      } else {
        // 创建新作品
        response = await createArticleAPI(articleData);
      }
      
      if (response.success) {
        onSave && onSave(response.data);
        message.success('草稿保存成功');
        
        // 如果是新作品，保存后跳转到作品列表
        if (!articleId) {
          setTimeout(() => {
            navigate('/articles');
          }, 1000);
        }
      } else {
        message.error(response.message || '保存失败');
      }
      
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 发布作品
  const handlePublish = async () => {
    if (!article.title.trim()) {
      message.error('请输入作品标题');
      return;
    }

    if (!article.content.html || article.content.html.trim() === '<p></p>') {
      message.error('请输入作品内容');
      return;
    }

    try {
      setLoading(true);
      
      const articleData = {
        title: article.title,
        content: article.content.json,
        content_html: article.content.html,
        cover_image: article.coverImage,
        status: 'published'
      };

      let response;
      if (articleId) {
        // 更新现有作品
        response = await updateArticleAPI(articleId, articleData);
      } else {
        // 创建新作品
        response = await createArticleAPI(articleData);
      }
      
      if (response.success) {
        onPublish && onPublish(response.data);
        message.success('作品发布成功');
        
        // 发布后跳转到作品列表
        setTimeout(() => {
          navigate('/articles');
        }, 1000);
      } else {
        message.error(response.message || '发布失败');
      }
      
    } catch (error) {
      console.error('发布失败:', error);
      message.error('发布失败');
    } finally {
      setLoading(false);
    }
  };

  // 预览作品
  const handlePreview = () => {
    if (!article.content.html) {
      message.warning('暂无内容可预览');
      return;
    }
    setPreviewVisible(true);
  };

  return (
    <div className="article-editor">
      <Card className="editor-header">
        <Space direction="vertical" style={{ width: '100%' }}>
          {/* 作品标题 */}
          <Input
            placeholder="请输入作品标题..."
            value={article.title}
            onChange={handleTitleChange}
            size="large"
            style={{ fontSize: 24, fontWeight: 'bold' }}
          />

          {/* 封面图片 */}
          <div className="cover-upload">
            <Space align="start">
              <Upload
                accept="image/*"
                beforeUpload={handleCoverUpload}
                showUploadList={false}
              >
                <Button icon={<PictureOutlined />}>
                  {article.coverImage ? '更换封面' : '上传封面'}
                </Button>
              </Upload>
              
              {article.coverImage && (
                <div className="cover-preview">
                  <Image
                    src={article.coverImage}
                    alt="封面图片"
                    width={120}
                    height={80}
                    style={{ objectFit: 'cover', borderRadius: 4 }}
                  />
                </div>
              )}
            </Space>
          </div>

          {/* 操作按钮 */}
          <Space>
            <Button 
              icon={<SaveOutlined />} 
              onClick={handleSave}
              loading={loading}
            >
              保存草稿
            </Button>
            <Button 
              icon={<EyeOutlined />} 
              onClick={handlePreview}
            >
              预览
            </Button>
            <Button 
              type="primary"
              icon={<SendOutlined />} 
              onClick={handlePublish}
              loading={loading}
            >
              发布作品
            </Button>
          </Space>
        </Space>
      </Card>

      {/* 编辑器标签页 */}
      <Card className="editor-content">
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="富文本编辑" key="editor" icon={<FileTextOutlined />}>
            <RichTextEditor
              content={article.content.html}
              onChange={handleContentChange}
              placeholder="开始写作你的精彩内容..."
            />
          </TabPane>
          
          <TabPane tab="文档管理" key="upload" icon={<UploadOutlined />}>
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <FileUpload
                onFileConverted={handleFileUploaded}
                maxFiles={10}
              />
              
              {uploadedDocuments.length > 0 && (
                <DocumentManager
                  documents={uploadedDocuments}
                  onDelete={handleDocumentDelete}
                  onView={insertDocumentContent}
                />
              )}
            </Space>
          </TabPane>
        </Tabs>
      </Card>

      {/* 预览模态框 */}
      <Modal
        title={article.title || '作品预览'}
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width="80%"
        className="article-preview-modal"
      >
        <div className="article-preview">
          {article.coverImage && (
            <div className="preview-cover">
              <img src={article.coverImage} alt="封面" />
            </div>
          )}
          
          <div className="preview-title">
            <h1>{article.title}</h1>
          </div>
          
          <div 
            className="preview-content"
            dangerouslySetInnerHTML={{ __html: article.content.html }}
          />
        </div>
      </Modal>
    </div>
  );
};

export default ArticleEditor;